package it.blueocean.acanto.taglibrary.jsp.taglib.tags;

import it.blueocean.acanto.taglibrary.jsp.taglib.tags.dataset.DataSet;
import it.blueocean.acanto.taglibrary.jsp.taglib.tags.dataset.PageCachedDataSet;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.jsp.JspException;
import javax.servlet.jsp.tagext.TagSupport;

import org.apache.taglibs.standard.lang.support.ExpressionEvaluatorManager;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;

public class LoadComponentsTag extends TagSupport
{
	private static final long serialVersionUID = -4576747146453300626L;

	private final static Logger logger_ = LoggerFactory.getLogger(LoadComponentsTag.class);

	private String compName_;

	private String compNameExpr_;

	public int doStartTag() throws JspException
	{
		evaluateExpressions();
		StateBeansManager localStateBeansManager = StateBeansManager.getInstance(this.pageContext.getSession());
		logger_.debug("looking up component: " + this.compName_);
		Object localObject = (AbstractComponentStateBean) localStateBeansManager.get(this.compName_);
		if(localObject instanceof DataSet)
			localObject = new PageCachedDataSet((DataSet) localObject);
		if(this.pageContext.getAttribute(this.compName_) == null)
			this.pageContext.setAttribute(this.compName_, localObject);
		else
			logger_.warn("An object with the same name was found in the page trying to import component "
					+ this.compName_ + " in page "
					+ ((HttpServletRequest) this.pageContext.getRequest()).getRequestURI());
		return 6;
	}

	public void setCompName(String paramString)
	{
		this.compNameExpr_ = paramString;
	}

	private void evaluateExpressions() throws JspException
	{
		if(this.compNameExpr_ != null)
			this.compName_ = ((String) ExpressionEvaluatorManager.evaluate("compName", this.compNameExpr_,
					String.class, this, this.pageContext));
		else
			this.compName_ = null;
	}
}
